{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-11-27T08:50:56.821967Z",
     "start_time": "2024-11-27T08:50:56.814446600Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---> 本轮k.shape=torch.Size([2, 1, 64])\n",
      "Output shape at time step 0: torch.Size([2, 1, 64])\n",
      "past_k shape: torch.Size([2, 1, 64])\n",
      "past_v shape: torch.Size([2, 1, 64])\n",
      "---> 本轮k.shape=torch.Size([2, 2, 64])\n",
      "Output shape at time step 1: torch.Size([2, 1, 64])\n",
      "past_k shape: torch.Size([2, 2, 64])\n",
      "past_v shape: torch.Size([2, 2, 64])\n",
      "---> 本轮k.shape=torch.Size([2, 3, 64])\n",
      "Output shape at time step 2: torch.Size([2, 1, 64])\n",
      "past_k shape: torch.Size([2, 3, 64])\n",
      "past_v shape: torch.Size([2, 3, 64])\n",
      "---> 本轮k.shape=torch.Size([2, 4, 64])\n",
      "Output shape at time step 3: torch.Size([2, 1, 64])\n",
      "past_k shape: torch.Size([2, 4, 64])\n",
      "past_v shape: torch.Size([2, 4, 64])\n",
      "---> 本轮k.shape=torch.Size([2, 5, 64])\n",
      "Output shape at time step 4: torch.Size([2, 1, 64])\n",
      "past_k shape: torch.Size([2, 5, 64])\n",
      "past_v shape: torch.Size([2, 5, 64])\n"
     ]
    }
   ],
   "source": [
    "# kvcache原理：https://zhuanlan.zhihu.com/p/662498827?utm_id=0\n",
    "# kvcache代码实现：https://blog.csdn.net/Ephemeroptera/article/details/140323157\n",
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import math\n",
    "\n",
    "class StreamSelfAttention(nn.Module):\n",
    "    def __init__(self, model_dim, attention_size):\n",
    "        super(StreamSelfAttention, self).__init__()\n",
    "        self.model_dim = model_dim\n",
    "        self.attention_size = attention_size\n",
    "        self.query_proj = nn.Linear(model_dim, model_dim)\n",
    "        self.key_proj = nn.Linear(model_dim, model_dim)\n",
    "        self.value_proj = nn.Linear(model_dim, model_dim)\n",
    "        self.softmax = nn.Softmax(dim=-1)\n",
    "        \n",
    "        self.k_cache = None\n",
    "        self.v_cache = None\n",
    "\n",
    "    def forward(self, x, past_k=None, past_v=None):\n",
    "        # Project inputs to Q, K, V\n",
    "        q = self.query_proj(x)  # (N, T, model_dim)\n",
    "        k = self.key_proj(x)  # (N, T, model_dim)\n",
    "        v = self.value_proj(x)  # (N, T, model_dim)\n",
    "        \n",
    "        batch_size = x.size(0)\n",
    "        seq_len = x.size(1)\n",
    "        \n",
    "        # 初始化缓存\n",
    "        # Initialize past_k and past_v if not provided\n",
    "        if past_k is None:\n",
    "            past_k = torch.zeros((batch_size, 0, self.model_dim), device=x.device)\n",
    "            past_v = torch.zeros((batch_size, 0, self.model_dim), device=x.device)\n",
    "        \n",
    "        # Concatenate past K, V with current K, V\n",
    "        k = torch.cat([past_k, k], dim=1)  # (N, seq_len + T, model_dim)\n",
    "        v = torch.cat([past_v, v], dim=1)  # (N, seq_len + T, model_dim)\n",
    "        \n",
    "        print(f'---> 本轮k.shape={k.shape}')\n",
    "        \n",
    "        # 裁剪缓存，为了限制计算复杂度，我们将缓存裁剪到指定的注意力窗口大小\n",
    "        # Trim cache to the attention size\n",
    "        if k.size(1) > self.attention_size:\n",
    "            k = k[:, -self.attention_size:]  # (N, attention_size, model_dim)\n",
    "            v = v[:, -self.attention_size:]  # (N, attention_size, model_dim)\n",
    "    \n",
    "        # Compute attention scores\n",
    "        attn_scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.model_dim)  # (N, T, attention_size)\n",
    "        attn_weights = self.softmax(attn_scores)  # (N, T, attention_size)\n",
    "        \n",
    "        # Compute attention output\n",
    "        attn_output = torch.matmul(attn_weights, v)  # (N, T, model_dim)\n",
    "        \n",
    "        # Update caches\n",
    "        self.k_cache = k\n",
    "        self.v_cache = v\n",
    "        \n",
    "        return attn_output, self.k_cache, self.v_cache\n",
    "    \n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    batch_size = 2\n",
    "    model_dim = 64\n",
    "    attention_size = 10\n",
    "    seq_len = 1\n",
    "\n",
    "    # Instantiate the self-attention layer\n",
    "    self_attn = StreamSelfAttention(model_dim, attention_size)\n",
    "    \n",
    "    past_k = past_v = None\n",
    "    for t in range(5):\n",
    "        x = torch.rand(batch_size, seq_len, model_dim)  # Simulating input at time step t\n",
    "        output, past_k, past_v = self_attn(x, past_k, past_v)\n",
    "        print(f\"Output shape at time step {t}: {output.shape}\")  # (N, T, model_dim)\n",
    "        print(f\"past_k shape: {past_k.shape}\")  # (N, seq_len + T, model_dim)\n",
    "        print(f\"past_v shape: {past_v.shape}\")  # (N, seq_len + T, model_dim)\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
